package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autofillPointCut() {


    }

    @Before("autofillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        LocalDateTime now = LocalDateTime.now();
        Long CurrentId = BaseContext.getCurrentId();
        Object target = args[0];
        if(target == null){
            return ;
        }
        if(operationType == OperationType.INSERT){
            //插入四个数据
            Method setcreateTime = target.getClass().getDeclaredMethod("setCreateTime",LocalDateTime.class);
            Method setupdateTime = target.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setcreateUser = target.getClass().getDeclaredMethod("setCreateUser", Long.class);
            Method setupdateUser = target.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            setcreateTime.invoke(target,now);
            setupdateTime.invoke(target,now);
            setcreateUser.invoke(target,CurrentId);
            setupdateUser.invoke(target,CurrentId);
        }
        else if(operationType == OperationType.UPDATE){
            Method setupdateTime = target.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setupdateUser = target.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            setupdateTime.invoke(target,now);
            setupdateUser.invoke(target,CurrentId);
        }

    }
}
